//
//  Codable+Dictionary.swift
//  SwiftCode
//
//  Created by yuhus on 2024/9/6.
//

import Foundation

public extension Encodable {
  var json: [String: Any] {
    do {
      let data = try JSONEncoder().encode(self)
      guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return [:] }
      return json
    } catch let error {
      assertionFailure(error.localizedDescription)
      return [:]
    }
  }
}

public extension Decodable {
  init?(json: [String: Any]) {
    do {
      let data = try JSONSerialization.data(withJSONObject: json, options: [])
      self = try JSONDecoder().decode(Self.self, from: data)
    } catch let error {
      debugPrint(#fileID, #line, Self.self, json)
      debugPrint(#fileID, #line, Self.self, error)
      return nil
    }
  }
  
  init?(jsonString: String) {
    do {
      guard let data = jsonString.data(using: .utf8) else {
        return nil
      }
      self = try JSONDecoder().decode(Self.self, from: data)
    } catch let error {
      debugPrint(#fileID, #line, Self.self, error)
      return nil
    }
  }
}
